package huaweiod.second;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 会议室占用时间段
 */
public class C9_MergeRoomTimes {

    static class Meet {
        public int start;
        public int end;

        public Meet(int start, int end) {
            this.start = start;
            this.end = end;
        }
    }

    public static int[][] merge(int[][] roomTimes) {
        List<Meet> meetList = new ArrayList<>();
        for (int i = 0; i < roomTimes.length; i++) {
            meetList.add(new Meet(roomTimes[i][0], roomTimes[i][1]));
        }
        meetList.sort(((o1, o2) -> {
            if (o1.start == o2.start) {
                return o1.end - o2.end;
            } else {
                return o1.start - o2.start;
            }
        }));

        List<Meet> res = new ArrayList<>();
        for (int i = 0; i < meetList.size(); i++) {
            int start = meetList.get(i).start;
            int end = meetList.get(i).end;
            for (int j = i + 1; j < meetList.size(); j++) {
                if (meetList.get(j).start <= end) {
                    end = meetList.get(j).end;
                    i++;
                } else {
                    break;
                }
            }
            res.add(new Meet(start,end));
        }
        int[][] ans = new int[res.size()][2];
        for (int i = 0; i < res.size(); i++) {
            ans[i][0] = res.get(i).start;
            ans[i][1] = res.get(i).end;
        }
        return ans;
    }

    public static void main(String[] args) {
        int[][] roomTimes = {{1, 4}, {2, 5}, {7, 9}, {14, 18}};
        int[][] merge = merge(roomTimes);
        System.out.println(Arrays.deepToString(merge));
    }
}
